module.exports = app => {

  const express = require('express')
  const router = express.Router({
    mergeParams: true
  })

  const jwt = require('jsonwebtoken')

  // 提交数据
  router.post('/', async (req, res) => {
    try{
      const model = await req.Model.create(req.body)
      res.send({ message: '添加成功!' })
    }catch(err){
      console.log(err.message);
      if(req.params.resource == 'login') {
        return res.send({ message: '用户名已存在!' })
      }
      res.send({ message: '添加失败!' })
    }
  })

  // 获取数据
  router.get('/', async (req, res) => {
    const items = await req.Model.find({
      parent: undefined
    })
    res.send(items)
  })

  router.get('/whole', async (req, res) => {
    const queryOptions = {}
    const resource = req.params.resource
    if(resource == 'products') {
      queryOptions.populate = 'CategoryId'
    }
    if(resource == 'login') {
      queryOptions.populate = 'roleId'
    }
    const items = await req.Model.find().setOptions(queryOptions)
    res.send(items)
  })

  // 获取子分类
  router.post('/subclass', async (req, res) => {
    try {
      const model = await req.Model.find({
        parent: req.body._id,
      })
      res.send(model)
    } catch(err) {
      console.log(err.message)
    }
  })

  // 更新数据
  router.post('/update', async (req, res) => {
    try {
      await req.Model.updateOne({"_id": req.body._id}, {"$set": req.body})
      res.send({ message: '修改成功!' })
    } catch(err) {
      res.send({ message: '修改失败!' })
    }
  })

    // 删除数据
  router.delete('/delete', async (req, res) => {
    try {
      await req.Model.findByIdAndRemove(req.query._id)
      res.send({message: '删除成功!'})
    } catch(err) {
      console.log(err.message)
      res.send({message: '删除失败!'})
    }
  })

  // 根据用户名查询单个
  router.get('/user', async (req, res) => {  
    try {
      // const tokenData = jwt.verify(req.body.token, app.get('secret'))
      // const items = await req.Model.findById(tokenData.id)
      const queryOptions = {}
      const resource = req.params.resource
      if(resource == 'login') {
        queryOptions.populate = 'roleId'
      }
      const model = await req.Model.findOne({
        username: req.query.username,
      }).setOptions(queryOptions)
      res.send(model)
    } catch(err) {
      console.log('jwt err');
    }
  })

  // 拦截器
  app.use('/api/grain/rest/:resource', (req, res, next) => {
    let modelName = req.params.resource
    let str = modelName[0].toUpperCase()
    modelName = modelName.replace(modelName[0], str)

    req.Model = require(`../models/${modelName}`)
    next()
  }, router)

  // 上传图片
  const multer = require('multer')
  const upload = multer({ dest: __dirname + '/../upload' })
  app.post('/api/grain/upload', upload.single('file'), async (req, res) => {
    const url = `http://localhost:5000/upload/${req.file.filename}`
    const data = [{ alt: '图片', url}]
    res.send({
      "errno": 0,
      "data": data
    })
  })

  // 登录接口
  app.post('/api/grain/login', async (req, res) => {
    const Student = require('../models/Login')
    const { username, password } = req.body
    // 1. 根据用户名查找用户是否存在
    const user = await Student.findOne({ username }).select('+password')
    if(!user) {
      return res.send({
        state: 'warning',
        message: '账号不存在'
      })
    }
    // 2. 验证密码是否正确
    // const bool = require('bcrypt').compareSync(password, user.password)
    if(password !== user.password) {
      return res.send({
        state: 'error',
        message: '密码错误'
      })
    }
    const token = jwt.sign({ id: String(user._id) }, app.get('secret'))
    res.send({ 
      token,
      name: username,
      state: 'success',
      message: '登录成功'
     })
  })
  
}
